package service

import (
	"gorm.io/gorm"
	"gowork/microSignalSMSSending/dao"
	"gowork/microSignalSMSSending/dataInit"
	"gowork/microSignalSMSSending/utils"
)

type SMSRecordServiceImf struct {
	Tx *gorm.DB
	DistributionRecordsImf *dao.DistributionRecordsImf
	SendingModeRecordDaoImf *dao.SendingModeRecordDaoImf
	AuthorizationRecordsImf *dao.AuthorizationRecordsImf
	SMSRecordDaoImf *dao.SMSRecordDaoImf
}

func (sMSRecordServiceImf *SMSRecordServiceImf) SendWechat() (map[string]interface{}, error) {

	sMSRecordServiceImf.Tx = dataInit.Db.Begin()
	sMSRecordServiceImf.DistributionRecordsImf = new(dao.DistributionRecordsImf)
	sMSRecordServiceImf.SendingModeRecordDaoImf = new(dao.SendingModeRecordDaoImf)
	sMSRecordServiceImf.AuthorizationRecordsImf = new(dao.AuthorizationRecordsImf)
	sMSRecordServiceImf.SMSRecordDaoImf = new(dao.SMSRecordDaoImf)

	w := new(utils.Worker)

	smrList, err := sMSRecordServiceImf.SendingModeRecordDaoImf.GetSendingWeChatRecord(sMSRecordServiceImf.Tx)
	if err != nil{
		sMSRecordServiceImf.Tx.Rollback()
	}
	for _, smr := range smrList {
		sMSRecordServiceImf.SMSRecordDaoImf.InsertSMSRecord(w.GetId(), smr.CustomerId, sMSRecordServiceImf.Tx, smr.Phone, smr.WeChatCardUrl, smr.WeChatNo, smr.Content,  smr.CustomerName, smr.Account)
		sMSRecordServiceImf.SendingModeRecordDaoImf.UpdateIsSendById(smr.SendingModeRecordId, sMSRecordServiceImf.Tx)
	}

	awclist, err := sMSRecordServiceImf.AuthorizationRecordsImf.GetSendingWeChatRecord(sMSRecordServiceImf.Tx)
	if err != nil{
		sMSRecordServiceImf.Tx.Rollback()
	}
	for _, awc := range awclist {
		sMSRecordServiceImf.SMSRecordDaoImf.InsertSMSRecord(w.GetId(), awc.CustomerId, sMSRecordServiceImf.Tx, awc.Phone, awc.WeChatCardUrl, awc.WeChatNo, "", awc.CustomerName, awc.Account)
	}

	dwclist, err := sMSRecordServiceImf.DistributionRecordsImf.GetSendingWeChatRecord(sMSRecordServiceImf.Tx)
	if err != nil{
		sMSRecordServiceImf.Tx.Rollback()
	}
	for _, dwc := range dwclist {
		sMSRecordServiceImf.SMSRecordDaoImf.InsertSMSRecord(w.GetId(), dwc.CustomerId, sMSRecordServiceImf.Tx, dwc.Phone, dwc.WeChatCardUrl, dwc.WeChatNo, "", dwc.CustomerName, dwc.Account)
	}

	sMSRecordServiceImf.Tx.Commit()

	return map[string]interface{}{"code":200, "message":"新增成功"}, nil
}
